﻿using System;       
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ccit.ClassLibrary;
using System.Text;
using System.Data;
using Ccit.Utils;
using Ccit.SysPlat.Log;

namespace Ccit.SysPlat.Organ
{
    /// <summary>
    /// Description: 系统平台组织机构 -> 部门管理ACCESS数据实现层
    /// Author: tim 2010-01-29
    /// </summary>
    public class DeptAES : IDept
    {
        #region init error log interface
        private ILog _logInterface = null;
        private const string _funcPageName = "部门管理";
        public DeptAES()
        {
            _logInterface = Factory.CreateObject(MsErrLog.assemblyName, MsErrLog.className, 
                                                    ImportComponentType.DotNetDll, null) as ILog;
        }
        private string _multiDeptSign = HttpContext.Current.Application["MultiDept"].ToString();  //多部门多职位系统开关
        #endregion

        #region IDept 成员

        public MsDept GetDeptInfo(string deptId, eTrueFalse isContainExtend)
        {
            MsDept msDept = getDeptObject(deptId, isContainExtend);
            return msDept;
        }

        public List<MsDept> GetStairDeptList(string organId)
        {
            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT A.SYS_A2_10 AS DEPTID,A.SYS_A2_20 AS DEPTNAME,A.SYS_A2_60 AS ORDERNO,C.DEPTCOUNT ");
            sbCmdText.Append("FROM (SYS_A2 A ");
            sbCmdText.Append("INNER JOIN SYS_R5 B ON A.SYS_A2_10=B.SYS_R5_20) ");
            sbCmdText.Append("INNER JOIN (SELECT MID(SYS_A2_30,1,4) AS LAYCODE,COUNT(*) AS DEPTCOUNT FROM SYS_A2 ");
            sbCmdText.Append("WHERE SYS_A2_70='0' GROUP BY  MID(SYS_A2_30,1,4)) C ON A.SYS_A2_30=C.LAYCODE ");
            sbCmdText.Append("WHERE B.SYS_R5_10=").Append(organId).Append(" AND A.SYS_A2_70='0' AND LEN(A.SYS_A2_30)=4 ");
            sbCmdText.Append("ORDER BY A.SYS_A2_60 ASC");

            List<MsDept> lstDept = new List<MsDept>();
            try
            {
                MsDept msDept;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        msDept = new MsDept
                        {
                            deptId = iReader["DEPTID"].ToString(),
                            deptName = iReader["DEPTNAME"].ToString(),
                            orderNo = iReader["ORDERNO"].ToString(),
                            isHasChild = (Int32.Parse(iReader["DEPTCOUNT"].ToString()) > 1) ? "1" : "0"  //有无下级子节点
                        };
                        lstDept.Add(msDept);
                    }
                }
            }
            catch (FormatException ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "002", //数据类型转换异常
                    paramInfo = string.Empty
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            return lstDept;
        }

        public List<MsDept> GetSubDeptList(string deptId,string organId)
        {
            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT A.SYS_A2_10 AS DEPTID,A.SYS_A2_20 AS DEPTNAME,A.SYS_A2_60 AS ORDERNO,C.DEPTCOUNT ");
            sbCmdText.Append("FROM (((SYS_A2 A ");
            sbCmdText.Append("INNER JOIN SYS_R5 B ON A.SYS_A2_10=B.SYS_R5_20) ");
            sbCmdText.Append("INNER JOIN (SELECT SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_10=").Append(deptId).Append(") D ON A.SYS_A2_30 LIKE '' & D.LAYCODE & '%') ");
            sbCmdText.Append("INNER JOIN (SELECT MID(A.SYS_A2_30,1,(LEN(D.LAYCODE) + 4)) AS LAYCODE,COUNT(*) AS DEPTCOUNT ");
            sbCmdText.Append("FROM (SYS_A2 A ");
            sbCmdText.Append("INNER JOIN SYS_R5 B ON A.SYS_A2_10=B.SYS_R5_20) ");
            sbCmdText.Append("INNER JOIN (SELECT SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_10=").Append(deptId).Append(") D ON A.SYS_A2_30 LIKE '' & D.LAYCODE & '%' ");
            sbCmdText.Append("WHERE B.SYS_R5_10=").Append(organId).Append(" AND  LEN(A.SYS_A2_30) >= (LEN(D.LAYCODE) + 4) AND A.SYS_A2_70='0' ");
            sbCmdText.Append("GROUP BY MID(A.SYS_A2_30,1,(LEN(D.LAYCODE) + 4))) C ON C.LAYCODE=A.SYS_A2_30) ");
            sbCmdText.Append("WHERE B.SYS_R5_10=").Append(organId).Append(" AND  LEN(A.SYS_A2_30) = (LEN(D.LAYCODE) + 4) AND A.SYS_A2_70='0' ");
            sbCmdText.Append("ORDER BY A.SYS_A2_60 ASC");

            List<MsDept> lstDept = new List<MsDept>();
            try
            {
                MsDept msDept;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        msDept = new MsDept
                        {
                            deptId = iReader["DEPTID"].ToString(),
                            deptName = iReader["DEPTNAME"].ToString(),
                            orderNo = iReader["ORDERNO"].ToString(),
                            isHasChild = (Int32.Parse(iReader["DEPTCOUNT"].ToString()) > 1) ? "1" : "0"  //有无下级子节点
                        };
                        lstDept.Add(msDept);
                    }
                }
            }
            catch (FormatException ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "002", //数据类型转换异常
                    paramInfo = string.Empty
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbCmdText = null;
            return lstDept;
        }

        public List<string> Save(MsDept msDept)
        {
            List<string> lstResult = null;
            string deptId = msDept.deptId;

            if (string.IsNullOrEmpty(deptId))
                lstResult = addnew(msDept, _multiDeptSign);
            else
                lstResult = update(msDept, _multiDeptSign);

            return lstResult;
        }
               
        public List<string> Delete(string deptId)
        {
            List<string> lstResult = null;
            StringBuilder sbCmdText = new StringBuilder();
            List<string> lstCmdText = new List<string>();

            //'获取本部门及所有下级子部门Id串
            sbCmdText.Append("UPDATE SYS_A2 SET SYS_A2_70='1' WHERE SYS_A2_10 IN (");
            sbCmdText.Append("SELECT A.SYS_A2_10 AS DEPTID FROM SYS_A2 A ");
            sbCmdText.Append("INNER JOIN (SELECT SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_10=").Append(deptId).Append(") B ON A.SYS_A2_30 LIKE '' + B.LAYCODE + '%')");
            lstCmdText.Add(sbCmdText.ToString());

            //'删除部门用户关联关系
            sbCmdText.Remove(0, sbCmdText.ToString().Length);
            sbCmdText.Append("DELETE FROM SYS_R1 WHERE SYS_R1_20 IN (");
            sbCmdText.Append("SELECT A.SYS_A2_10 AS DEPTID FROM SYS_A2 A ");
            sbCmdText.Append("INNER JOIN (SELECT SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_10=").Append(deptId).Append(") B ON A.SYS_A2_30 LIKE '' + B.LAYCODE + '%')");
            lstCmdText.Add(sbCmdText.ToString());

            //'删除机构部门关系
            sbCmdText.Remove(0, sbCmdText.ToString().Length);
            sbCmdText.Append("DELETE FROM SYS_R5 WHERE SYS_R5_20 IN (");
            sbCmdText.Append("SELECT A.SYS_A2_10 AS DEPTID FROM SYS_A2 A ");
            sbCmdText.Append("INNER JOIN (SELECT SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_10=").Append(deptId).Append(") B ON A.SYS_A2_30 LIKE '' + B.LAYCODE + '%')");
            lstCmdText.Add(sbCmdText.ToString());

            try
            {
                int iexe = DataAccessor.ExecuteNonQuery(lstCmdText);

                sbCmdText = null;
                lstCmdText = null;
                if (iexe > 0) lstResult = new List<string> { deptId, "删除成功!" };
                else lstResult = new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            }
            catch (Exception ex)
            {

                StringBuilder sbParam = new StringBuilder();
                int sqlIndex = 1;
                foreach (string eSQL in lstCmdText)
                {
                    sbParam.Append("<SQL" + sqlIndex.ToString()).Append("><![CDATA[").Append(eSQL);
                    sbParam.Append("]]></SQL" + sqlIndex.ToString() + ">");
                }
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = sbParam.ToString()
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                sbParam = null;
                lstResult = new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            }

            lstCmdText = null;
            sbCmdText = null;
            return lstResult;
        }

        public string GetDeptLevelStruct(string deptId)
        {
            MsDept msDept = getDeptObject(deptId, eTrueFalse.FALSE);  //获取部门消息对象
            if (null == msDept) return string.Empty;

            string layCode = msDept.layCode;
            int layCodeLen = layCode.Length;
            int iLevel = layCodeLen / 4;

            string whereClause = " 1=1 AND SYS_A2_70='0' ";
            string subClause = string.Empty;
            string qryClause = string.Empty;
            for (int i = (iLevel - 1); i >= 0; i--)
            {
                subClause = "MID('" + layCode + "',1," + (layCodeLen - i * 4).ToString() + ")";
                qryClause += (string.IsNullOrEmpty(qryClause)) ? subClause : "," + subClause;
            }

            whereClause += (!string.IsNullOrEmpty(qryClause)) ? "AND SYS_A2_30 IN (" + qryClause + ")" : "AND 1>1";
            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT SYS_A2_10 AS DEPTID FROM SYS_A2 WHERE").Append(whereClause);
            sbCmdText.Append(" ORDER BY SYS_A2_30 ASC");

            string structIds = string.Empty;
            try
            {
                string tempDeptId = string.Empty;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        tempDeptId = iReader["DEPTID"].ToString();
                        structIds += (string.IsNullOrEmpty(structIds)) ? tempDeptId : "," + tempDeptId;
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            msDept = null;
            sbCmdText = null;
            return structIds;
                                
        }

        public List<MsKeyValue> GetALLDepts(string organId, string filterDeptId)
        {
            StringBuilder sbCmdText = new StringBuilder();
            StringBuilder sbWhereClause = new StringBuilder();
            sbWhereClause.Append("B.SYS_R5_10=").Append(organId).Append(" AND A.SYS_A2_70='0' ");
            if (!string.IsNullOrEmpty(filterDeptId))
            {
                string qryCon = "AND A.SYS_A2_30 NOT LIKE '' + (SELECT SYS_A2_30 FROM SYS_A2 WHERE SYS_A2_10=" + filterDeptId + ") + '%'";
                sbWhereClause.Append(qryCon);
            }

            sbCmdText.Append("SELECT A.SYS_A2_10 AS DEPTID,A.SYS_A2_20 AS DEPTNAME ");
            sbCmdText.Append("FROM SYS_A2 A INNER JOIN SYS_R5 B ON A.SYS_A2_10=B.SYS_R5_20 WHERE ");
            sbCmdText.Append(sbWhereClause.ToString());
            sbCmdText.Append(" ORDER BY A.SYS_A2_30 ASC");

            List<MsKeyValue> lstDept = new List<MsKeyValue>();
            try
            {
                MsKeyValue msKeyVal;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        msKeyVal = new MsKeyValue
                        {
                            key = iReader["DEPTID"].ToString(),
                            val = iReader["DEPTNAME"].ToString()
                        };
                        lstDept.Add(msKeyVal);
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbWhereClause = null;
            sbCmdText = null;
            return lstDept;
        }

        public bool IsExistSameName(string deptId, string deptName, string organId)
        {
            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT SYS_A2_10 AS DEPTID FROM SYS_A2 ");
            sbCmdText.Append("WHERE SYS_A2_20='").Append(deptName.Trim().Replace("'", "''")).Append("' AND ");
            sbCmdText.Append("SYS_A2_10 IN (SELECT SYS_R5_20 FROM SYS_R5 WHERE SYS_R5_10=").Append(organId).Append(")");

            bool bExist = false;
            try
            {
                string tempDeptId = string.Empty;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    if (iReader.Read())
                    {
                        tempDeptId = iReader["DEPTID"].ToString();
                    }
                }

                bExist = (string.IsNullOrEmpty(tempDeptId) || (tempDeptId == deptId)) ? false : true;
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbCmdText = null;
            return bExist;
        }

        public List<MsKeyValue> GetDeptListByIds(string deptIds, string findDeptName)
        {
            if (string.IsNullOrEmpty(deptIds)) return new List<MsKeyValue>();

            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT SYS_A2_10 AS DEPTID,SYS_A2_20 AS DEPTNAME FROM SYS_A2 ");
            sbCmdText.Append("WHERE 1=1 AND SYS_A2_10 IN (").Append(deptIds).Append(")");
            
            if (!string.IsNullOrEmpty(findDeptName))
                sbCmdText.Append(" AND SYS_A2_20 LIKE '%").Append(findDeptName).Append("%'");

            sbCmdText.Append("ORDER BY SYS_A2_60 ASC");

            List<MsKeyValue> lstDept = new List<MsKeyValue>();
            try
            {
                MsKeyValue msDept;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        msDept = new MsKeyValue
                        {
                            key = iReader["DEPTID"].ToString(),
                            val = iReader["DEPTNAME"].ToString()
                        };
                        lstDept.Add(msDept);
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbCmdText = null;
            return lstDept;
        }

        public List<MsKeyValue> GetDeptListByOrgan(string organId, string filterDeptIds, string findDeptName)
        {
            /* 业务逻辑修改说明:
            *     对部门名称是否可以重复通过增加系统开关的方式处理
            *     因此，如果对于允许部门名称重复的情况下，则需要将部门统一按层级方式显示。否则会影响部门的选取
            * Modifier: tim 2010-03-17 */

            StringBuilder sbCmdText = new StringBuilder();
            string whereClause = string.Empty;
            if (!string.IsNullOrEmpty(filterDeptIds))
            {
                whereClause = " AND A.SYS_A2_10 NOT IN (" + filterDeptIds + ")";
            }

            if (!string.IsNullOrEmpty(findDeptName))
            {
                whereClause += " AND A.SYS_A2_20 LIKE '%" + findDeptName + "%'";
            }

            sbCmdText.Append("SELECT A.SYS_A2_10 AS DEPTID,A.SYS_A2_20 AS DEPTNAME,A.SYS_A2_30 AS LAYCODE ");
            sbCmdText.Append("FROM SYS_A2 A INNER JOIN SYS_R5 B ON A.SYS_A2_10=B.SYS_R5_20 ");
            sbCmdText.Append("WHERE B.SYS_R5_10=").Append(organId).Append(" AND A.SYS_A2_70='0'").Append(whereClause);
            sbCmdText.Append(" ORDER BY A.SYS_A2_30 ASC,A.SYS_A2_60 ASC");

            List<MsKeyValue> lstDept = new List<MsKeyValue>();
            try
            {
                MsKeyValue msDept = null;
                string layCode = string.Empty;
                int bmLen = 0;
                string indPrefix = string.Empty; //缩进前缀
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        layCode = iReader["LAYCODE"].ToString();
                        bmLen = layCode.Length / 4;
                        indPrefix = string.Empty;
                        for (int j = 0; j < bmLen - 1; j++)
                        {
                            indPrefix += "\u3000";
                        }

                        msDept = new MsKeyValue {
                            key = iReader["DEPTID"].ToString(),
                            val = indPrefix + iReader["DEPTNAME"].ToString()
                        };
                        lstDept.Add(msDept);
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbCmdText = null;
            return lstDept;
        }

        public string GetDeptNamesByIds(string deptIds, string separator)
        {
            if (string.IsNullOrEmpty(deptIds)) return string.Empty;
                        
            string cmdText = "SELECT SYS_A2_20 AS DEPTNAME FROM SYS_A2 WHERE SYS_A2_10 IN (" + deptIds + ")";

            string deptNames = string.Empty;
            string deptName = string.Empty;
            try
            {
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while (iReader.Read())
                    {
                        deptName = iReader["DEPTNAME"].ToString();
                        deptNames += (string.IsNullOrEmpty(deptNames)) ? deptName : separator + deptName;
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            return deptNames;
        }

        public string GetDeptNamesByIds(string deptIds, string separator, eTrueFalse isFilter)
        {
            if (string.IsNullOrEmpty(deptIds)) return string.Empty;

            string deptNames = string.Empty;
            if (isFilter == eTrueFalse.TRUE)
            {               
                string cmdText = "SELECT SYS_A2_20 AS DEPTNAME FROM SYS_A2 WHERE SYS_A2_10 IN (" + deptIds + ")  AND SYS_A2_70='0'";
                string deptName = string.Empty;
                try
                {
                    using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                    {
                        while (iReader.Read())
                        {
                            deptName = iReader["DEPTNAME"].ToString();
                            deptNames += (string.IsNullOrEmpty(deptNames)) ? deptName : separator + deptName;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MsErrLog msErrorLog = new MsErrLog
                    {
                        funcPageName = _funcPageName,
                        errMsg = ex.Message,
                        codeTrack = ex.StackTrace,
                        errClassCode = "001", //SQL 异常
                        paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                    };

                    _logInterface.WriteErrorLog(msErrorLog);
                    msErrorLog = null;
                }
            }
            else
            {
                deptNames = GetDeptNamesByIds(deptIds, separator);
            }

            return deptNames;
        }

        public string findALLDeptIds(string deptIds)
        {
            if (string.IsNullOrEmpty(deptIds)) return string.Empty;

            List<string> lstLayCode = new List<string>();
            string cmdText = "SELECT SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_10 IN (" + deptIds + ")";
            try
            {
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while (iReader.Read())
                    {
                        lstLayCode.Add(iReader["LAYCODE"].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                return string.Empty;
            }

            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT SYS_A2_10 AS DEPTID,SYS_A2_30 AS LAYCODE FROM SYS_A2 ");
            sbCmdText.Append("WHERE 1=1 AND SYS_A2_70='0'");
            int lIndex = 0;
            foreach (string eLayCode in lstLayCode)
            {
                if (lIndex == 0)
                    sbCmdText.Append(" (SYS_A2_30 LIKE '").Append(eLayCode).Append("%')");
                else
                    sbCmdText.Append(" OR (SYS_A2_30 LIKE '").Append(eLayCode).Append("%')");
                lIndex++;
            }
            sbCmdText.Append(" ORDER BY SYS_A2_30,SYS_A2_60");

            string retDeptIds = string.Empty;
            string deptId = string.Empty;
            try
            {
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        deptId = iReader["DEPTID"].ToString();
                        retDeptIds += (string.IsNullOrEmpty(retDeptIds)) ? deptId : "," + deptId;
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            return retDeptIds;
        }

        public List<MsDept> GetStairDeptListForMobile(string organId)
        {
            if (string.IsNullOrEmpty(organId)) return new List<MsDept>();

            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT A.SYS_A2_10 AS DEPTID,A.SYS_A2_20 AS DEPTNAME,A.SYS_A2_60 AS ORDERNO,C.DEPTCOUNT,IIF(ISNULL(D.USERCOUNT),0,D.USERCOUNT) AS USERCOUNT ");
            sbCmdText.Append("FROM ((SYS_A2 A ");
            sbCmdText.Append("INNER JOIN SYS_R5 B ON A.SYS_A2_10=B.SYS_R5_20) ");
            sbCmdText.Append("INNER JOIN (SELECT MID(SYS_A2_30,1,4) AS LAYCODE,COUNT(*) AS DEPTCOUNT FROM SYS_A2 ");
            sbCmdText.Append("WHERE SYS_A2_70='0' GROUP BY MID(SYS_A2_30,1,4)) C ON A.SYS_A2_30=C.LAYCODE) ");
            sbCmdText.Append("LEFT JOIN (SELECT COUNT(A.SYS_A1_10) AS USERCOUNT,B.SYS_R1_20 FROM ((SELECT SYS_A2_10 AS DEPTID FROM SYS_A2 A1 ");
            sbCmdText.Append("INNER JOIN SYS_R5 A2 ON A1.SYS_A2_10=A2.SYS_R5_20 ");
            sbCmdText.Append("WHERE A2.SYS_R5_10=").Append(organId).Append(" AND A1.SYS_A2_70='0' AND LEN(A1.SYS_A2_30)=4) C ");
            sbCmdText.Append("LEFT JOIN SYS_R1 B ON B.SYS_R1_20=C.DEPTID) ");
            sbCmdText.Append("LEFT JOIN SYS_A1 A ON A.SYS_A1_10 =B.SYS_R1_10 ");
            sbCmdText.Append("WHERE A.SYS_A1_90='0' GROUP BY B.SYS_R1_20");
            sbCmdText.Append(") D ON D.SYS_R1_20=A.SYS_A2_10 ");
            sbCmdText.Append("WHERE B.SYS_R5_10=").Append(organId).Append(" AND A.SYS_A2_70='0' AND LEN(A.SYS_A2_30)=4 ");
            sbCmdText.Append("ORDER BY A.SYS_A2_60 ASC");

            List<MsDept> lstDept = new List<MsDept>();
            try
            {
                MsDept msDept;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        msDept = new MsDept
                        {
                            deptId = iReader["DEPTID"].ToString(),
                            deptName = iReader["DEPTNAME"].ToString(),
                            orderNo = iReader["ORDERNO"].ToString(),
                            isHasChild = (Int32.Parse(iReader["DEPTCOUNT"].ToString()) > 1 || Int32.Parse(iReader["USERCOUNT"].ToString()) > 0) ? "1" : "0"  //有无下级子节点
                        };
                        lstDept.Add(msDept);
                    }
                }
            }
            catch (FormatException ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "002", //数据类型转换异常
                    paramInfo = string.Empty
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbCmdText = null;
            return lstDept;
        }

        public List<MsDept> GetSubDeptListForMobile(string deptId, string organId)
        {

            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT A.SYS_A2_10 AS DEPTID,A.SYS_A2_20 AS DEPTNAME,A.SYS_A2_60 AS ORDERNO,C.DEPTCOUNT,IIF(ISNULL(E.USERCOUNT),0,E.USERCOUNT) AS USERCOUNT ");
            sbCmdText.Append("FROM (((SYS_A2 A ");
            sbCmdText.Append("INNER JOIN SYS_R5 B ON A.SYS_A2_10=B.SYS_R5_20) ");
            sbCmdText.Append("INNER JOIN (SELECT SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_10=").Append(deptId).Append(") D ON A.SYS_A2_30 LIKE '' + D.LAYCODE + '%') ");
            sbCmdText.Append("INNER JOIN (SELECT MID(A.SYS_A2_30,1,(LEN(D.LAYCODE) + 4)) AS LAYCODE,COUNT(*) AS DEPTCOUNT ");
            sbCmdText.Append("FROM (SYS_A2 A ");
            sbCmdText.Append("INNER JOIN SYS_R5 B ON A.SYS_A2_10=B.SYS_R5_20) ");
            sbCmdText.Append("INNER JOIN (SELECT SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_10=").Append(deptId).Append(") D ON A.SYS_A2_30 LIKE '' + D.LAYCODE + '%' ");
            sbCmdText.Append("WHERE B.SYS_R5_10=").Append(organId).Append(" AND  (LEN(A.SYS_A2_30) >= (LEN(D.LAYCODE) + 4) AND LEN(A.SYS_A2_30) <= (LEN(D.LAYCODE) + 8)) AND A.SYS_A2_70='0' ");
            sbCmdText.Append("GROUP BY MID(A.SYS_A2_30,1,(LEN(D.LAYCODE) + 4))) C ON C.LAYCODE=A.SYS_A2_30) ");
            sbCmdText.Append("LEFT JOIN (SELECT A1.DEPTID,COUNT(A2.SYS_A1_10) AS USERCOUNT FROM ");
            sbCmdText.Append("((SELECT A.SYS_A2_10 AS DEPTID FROM (SYS_A2 A ");
            sbCmdText.Append("INNER JOIN SYS_R5 B ON A.SYS_A2_10=B.SYS_R5_20) ");
            sbCmdText.Append("INNER JOIN (SELECT SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_10=").Append(deptId).Append(") D ON A.SYS_A2_30 LIKE '' + D.LAYCODE + '%' ");
            sbCmdText.Append("WHERE B.SYS_R5_10=").Append(organId).Append(" AND  LEN(A.SYS_A2_30) = (LEN(D.LAYCODE) + 4) AND A.SYS_A2_70='0' ) A1 ");
            sbCmdText.Append("LEFT JOIN SYS_R1 R1 ON R1.SYS_R1_20=A1.DEPTID) ");
            sbCmdText.Append("LEFT JOIN SYS_A1 A2 ON A2.SYS_A1_10=R1.SYS_R1_10 ");
            sbCmdText.Append("WHERE A2.SYS_A1_90='0' GROUP BY A1.DEPTID ");
            sbCmdText.Append(") E ON E.DEPTID=A.SYS_A2_10 ");
            sbCmdText.Append("WHERE B.SYS_R5_10=").Append(organId).Append(" AND  LEN(A.SYS_A2_30) = (LEN(D.LAYCODE) + 4) AND A.SYS_A2_70='0' ");
            sbCmdText.Append("ORDER BY A.SYS_A2_60 ASC");

            List<MsDept> lstDept = new List<MsDept>();
            try
            {
                MsDept msDept;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        msDept = new MsDept
                        {
                            deptId = iReader["DEPTID"].ToString(),
                            deptName = iReader["DEPTNAME"].ToString(),
                            orderNo = iReader["ORDERNO"].ToString(),
                            isHasChild = (Int32.Parse(iReader["DEPTCOUNT"].ToString()) > 1 || Int32.Parse(iReader["USERCOUNT"].ToString()) > 0) ? "1" : "0"  //有无下级子节点
                        };
                        lstDept.Add(msDept);
                    }
                }
            }
            catch (FormatException ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "002", //数据类型转换异常
                    paramInfo = string.Empty
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbCmdText = null;
            return lstDept;

        }
        #endregion


        #region private methods
        /// <summary>
        /// 获取部门消息对象
        /// </summary>
        /// <param name="deptId">部门Id</param>
        /// <param name="isContainExtend">是否获取扩展属性</param>
        /// <returns></returns>
        private MsDept getDeptObject(string deptId, eTrueFalse isContainExtend)
        {
            StringBuilder sbCmdText = new StringBuilder();
            if (isContainExtend == eTrueFalse.FALSE)
            {
                sbCmdText.Append("SELECT A.SYS_A2_10 AS DEPTID,A.SYS_A2_20 AS DEPTNAME,A.SYS_A2_30 AS LAYCODE,A.SYS_A2_40 AS DEPTDESC,");
                sbCmdText.Append("A.SYS_A2_50 AS ADMINUSERID,A.SYS_A2_60 AS ORDERNO,A.SYS_A2_70 AS DELSIGN,B.SYS_A1_40 AS ADMINUSERNAME ");
                sbCmdText.Append("FROM SYS_A2 A ");
                sbCmdText.Append("LEFT JOIN SYS_A1 B ON A.SYS_A2_50=B.SYS_A1_10 ");
                sbCmdText.Append("WHERE A.SYS_A2_10=").Append(deptId);
            }
            else
            {
                //? 空缺 需要获取设置belongOrgan和includeUsers属性
                sbCmdText.Append("SELECT A.SYS_A2_10 AS DEPTID,A.SYS_A2_20 AS DEPTNAME,A.SYS_A2_30 AS LAYCODE,A.SYS_A2_40 AS DEPTDESC,");
                sbCmdText.Append("A.SYS_A2_50 AS ADMINUSERID,A.SYS_A2_60 AS ORDERNO,A.SYS_A2_70 AS DELSIGN,B.SYS_A1_40 AS ADMINUSERNAME,");
                sbCmdText.Append("D.SYS_A4_10 AS ORGID,D.SYS_A4_20 AS ORGNAME,D.SYS_A4_30 AS ORGCODE,D.SYS_A4_40 AS ORGLAYCODE,");
                sbCmdText.Append("D.SYS_A4_50 AS ORGDESC,D.SYS_A4_60 AS ORGORDERNO,D.SYS_A4_70 AS ORGEFFECTSIGN,E.SYS_A2_10 AS UPDEPTID ");
                sbCmdText.Append("FROM (((SYS_A2 A ");
                sbCmdText.Append("LEFT JOIN SYS_A1 B ON A.SYS_A2_50=B.SYS_A1_10) ");
                sbCmdText.Append("INNER JOIN SYS_R5 C ON A.SYS_A2_10=C.SYS_R5_20) ");
                sbCmdText.Append("INNER JOIN SYS_A4 D ON C.SYS_R5_10=D.SYS_A4_10) ");
                sbCmdText.Append("LEFT JOIN SYS_A2 E ON MID(A.SYS_A2_30,1,(LEN(A.SYS_A2_30) - 4))=E.SYS_A2_30 ");
                sbCmdText.Append("WHERE A.SYS_A2_10=").Append(deptId);
            }

            MsDept msDept = null;
            try
            {
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    if (iReader.Read() && null != iReader[0])
                    {
                        msDept = new MsDept
                        {
                            deptId = iReader["DEPTID"].ToString(),
                            deptName = iReader["DEPTNAME"].ToString(),
                            layCode = iReader["LAYCODE"].ToString(),
                            deptDesc = iReader["DEPTDESC"].ToString(),
                            adminUserId = iReader["ADMINUSERID"].ToString(),
                            orderNo = iReader["ORDERNO"].ToString(),
                            delSign = iReader["DELSIGN"].ToString(),
                            adminUserName = iReader["ADMINUSERNAME"].ToString(),
                            upDeptId = (isContainExtend == eTrueFalse.TRUE) ? iReader["UPDEPTID"].ToString() : string.Empty,
                            belongOrgan = (isContainExtend == eTrueFalse.FALSE) ? null : new MsOrgan
                            {
                                organId = iReader["ORGID"].ToString(),
                                organName = iReader["ORGNAME"].ToString(),
                                organCode = iReader["ORGCODE"].ToString(),
                                layCode = iReader["ORGLAYCODE"].ToString(),
                                organDesc = iReader["ORGDESC"].ToString(),
                                orderNo = iReader["ORGORDERNO"].ToString(),
                                effectSign = iReader["ORGEFFECTSIGN"].ToString()
                            }
                        };
                    }
                }

                if (isContainExtend == eTrueFalse.TRUE)
                {
                    sbCmdText.Remove(0, sbCmdText.ToString().Length);
                    sbCmdText.Append("SELECT SYS_A1_10 AS USERID,SYS_A1_40 AS USERNAME FROM SYS_A1 ");
                    sbCmdText.Append("WHERE SYS_A1_10 IN (SELECT SYS_R1_10 FROM SYS_R1 WHERE SYS_R1_20=").Append(deptId).Append(")");
                    string userId = string.Empty;
                    string userIds = string.Empty;
                    string userName = string.Empty;
                    string userNames = string.Empty;
                    using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                    {
                        while (iReader.Read())
                        {
                            userId = iReader["USERID"].ToString();
                            userName = iReader["USERNAME"].ToString();
                            userIds += (string.IsNullOrEmpty(userIds)) ? userId : "," + userId;
                            userNames += (string.IsNullOrEmpty(userName)) ? userName : " " + userName;
                        }
                    }

                    msDept.includeUsers = new MsKeyValue
                    {
                        key = userIds,
                        val = userNames
                    };
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbCmdText = null;
            return msDept;
        }

        /// <summary>
        /// 新增部门记录
        /// </summary>
        /// <param name="msDept">部门消息对象</param>
        /// <param name="multiDeptSign">多部门多职位系统开关 </param>
        /// <returns>
        ///     【0】:  部门记录Id / 负数 (操作失败)
        ///     【1】:  操作提示消息
        ///     【2】:  是否有下级子节点
        ///     【3】:  显示顺序
        /// </returns>
        private List<string> addnew(MsDept msDept, string multiDeptSign)
        {
            List<string> lstResult = null;
            string organId = msDept.belongOrgan.organId;  //部门所属机构
            string deptUserIds = msDept.includeUsers.key; //部门下用户
            string upDeptId = msDept.upDeptId; //上级部门Id

            List<string> lstCmdText = new List<string>();
            string cmdText = string.Empty;
            StringBuilder sbCmdText = new StringBuilder();

            #region 保存部门信息
            sbCmdText.Append("INSERT INTO SYS_A2 (SYS_A2_10,SYS_A2_20,SYS_A2_30,SYS_A2_40,SYS_A2_50,SYS_A2_60,SYS_A2_70) VALUES(");
            //string whereClause = "AND SYS_A2_10 IN (SELECT SYS_R5_20 FROM SYS_R5 WHERE SYS_R5_10=" + organId + ")";
            // 获取部门编码
            string deptLayCode = string.Empty;  //部门层级编码
            if (string.IsNullOrEmpty(upDeptId))
                deptLayCode = DataInterface.GetStairLayCode("SYS_A2", "SYS_A2_30", 4, string.Empty);
            else
                deptLayCode = DataInterface.GetNewSubLayCode("SYS_A2", "SYS_A2_30", 4, upDeptId, "SYS_A2_10", string.Empty);

            // 获取顺序号
            string orderNo = msDept.orderNo;
            int newOrder = 0;
            if (string.IsNullOrEmpty(orderNo))
            {
                newOrder = DataInterface.GetMaxId("SYS_A2", "SYS_A2_60");
                orderNo = newOrder.ToString();
            }
            
            string adminUserId = msDept.adminUserId;
            int newRecId = DataInterface.GetMaxId("SYS_A2", "SYS_A2_10");
            sbCmdText.Append("'").Append(newRecId.ToString()).Append("',");
            sbCmdText.Append("'").Append(msDept.deptName.Trim().Replace("'", "''")).Append("',");
            sbCmdText.Append("'").Append(deptLayCode).Append("',");
            sbCmdText.Append("'").Append(msDept.deptDesc.Replace("'", "''")).Append("',");
            if(!string.IsNullOrEmpty(adminUserId))
                sbCmdText.Append("'").Append(msDept.adminUserId).Append("',");
            else
                sbCmdText.Append("NULL,");
            sbCmdText.Append("'").Append(orderNo).Append("','0')");
            lstCmdText.Add(sbCmdText.ToString());
            #endregion

            #region 保存部门用户关系
            if (!string.IsNullOrEmpty(deptUserIds))
            {
                if (multiDeptSign == "0") //多部门多职位未开启,则应删除用户原先的部门关系
                {
                    cmdText = "DELETE FROM SYS_R1 WHERE SYS_R1_10 IN (" + deptUserIds + ")";
                    lstCmdText.Add(cmdText);
                }

                string[] userIdArray = deptUserIds.Split(',');
                foreach (string eUserId in userIdArray)
                {
                    cmdText = "INSERT INTO SYS_R1 (SYS_R1_10,SYS_R1_20,SYS_R1_30) VALUES (";
                    cmdText += "'" + eUserId + "',";
                    cmdText += "'" + newRecId.ToString() + "','0')";
                    lstCmdText.Add(cmdText);
                }
            }
            #endregion

            #region 保存机构部门关系
            cmdText = "INSERT INTO SYS_R5 (SYS_R5_10,SYS_R5_20) VALUES ('" + organId + "','" + newRecId.ToString() + "')";
            lstCmdText.Add(cmdText);

            #endregion

            try
            {
                int iexe = DataAccessor.ExecuteNonQuery(lstCmdText);
                if (iexe > 0)
                {
                    lstResult = new List<string> { newRecId.ToString(), "保存成功!" };
                    lstResult.Add("0");
                    lstResult.Add(orderNo);
                }
                else lstResult = new List<string> { "-1", "保存失败:服务器忙请稍后再试!", string.Empty, string.Empty };
            }
            catch (Exception ex)
            {
                StringBuilder sbParam = new StringBuilder();
                int sqlIndex = 1;
                foreach (string eSQL in lstCmdText)
                {
                    sbParam.Append("<SQL" + sqlIndex.ToString()).Append("><![CDATA[").Append(eSQL);
                    sbParam.Append("]]></SQL" + sqlIndex.ToString() + ">");
                    sqlIndex++;
                }
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = sbParam.ToString()
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                sbParam = null;
                lstResult = new List<string> { "-2", "操作失败:详情请参见错误日志!", string.Empty, string.Empty };
            }

            lstCmdText = null;
            sbCmdText = null;
            return lstResult;

        }

        /// <summary>
        /// 更新部门记录
        /// </summary>
        /// <param name="msDept">部门消息对象</param>
        /// <param name="multiDeptSign">多部门多职位系统开关</param>
        /// <returns>
        ///     【0】:  部门记录Id / 负数 (操作失败)
        ///     【1】:  操作提示消息
        ///     【2】:  是否有下级子节点
        ///     【3】:  显示顺序
        /// </returns>
        private List<string> update(MsDept msDept, string multiDeptSign)
        {
            List<string> lstResult = null;
            string deptId = msDept.deptId;
            string upDeptId = msDept.upDeptId;
            string cmdText = "SELECT SYS_A2_10 AS DEPTID,SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_10=" + deptId;

            MsDept msCurDept = null;  //当前部门的数据库信息
            string deptLayCode = string.Empty;
            StringBuilder sbCmdText = new StringBuilder();
            List<string> lstCmdText = new List<string>();
            sbCmdText.Append("UPDATE SYS_A2 SET SYS_A2_20='").Append(msDept.deptName.Trim().Replace("'","''")).Append("'");
            try {
                #region 获取当前部门的原层级编码
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    if (iReader.Read() && null != iReader[0])
                    {
                        msCurDept = new MsDept {
                            deptId = iReader["DEPTID"].ToString(),
                            layCode = iReader["LAYCODE"].ToString()
                        };
                    }
                }
                #endregion

                #region 更新部门信息
                List<bool> lstAlter = isAlterUpDept(deptId, upDeptId); //校验上级部门是否变更
                if (!lstAlter[0]) return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
                else { 
                    if(lstAlter[1])  //上级部门发生改变
                    {
                        deptLayCode = (string.IsNullOrEmpty(upDeptId)) ? DataInterface.GetStairLayCode("SYS_A2", "SYS_A2_30", 4, string.Empty) 
                                         : DataInterface.GetNewSubLayCode("SYS_A2", "SYS_A2_30", 4,upDeptId,"SYS_A2_10", string.Empty);
                        sbCmdText.Append(",SYS_A2_30='").Append(deptLayCode).Append("'");
                    }
                }
                sbCmdText.Append(",SYS_A2_40='").Append(msDept.deptDesc.Replace("'", "''")).Append("'");
                string adminUserId = msDept.adminUserId;
                if (string.IsNullOrEmpty(adminUserId))
                    sbCmdText.Append(",SYS_A2_50=NULL");
                else
                    sbCmdText.Append(",SYS_A2_50='").Append(adminUserId).Append("'");

                string orderNo = msDept.orderNo;
                if (!string.IsNullOrEmpty(orderNo))
                    sbCmdText.Append(",SYS_A2_60='").Append(orderNo).Append("'");

                sbCmdText.Append(" WHERE SYS_A2_10=").Append(deptId);
                lstCmdText.Add(sbCmdText.ToString());
                #endregion

                #region 变更所有子部门编码
                if (lstAlter[1])
                {
                    sbCmdText.Remove(0, sbCmdText.ToString().Length);
                    int newLayCodeLen = deptLayCode.Length; //部门新层级编码长度
                    string oriLayCode = msCurDept.layCode;  //部门原层级编码
                    int oriLayCodeLen = oriLayCode.Length;  //原层级编码长度
                    sbCmdText.Append("UPDATE SYS_A2 SET SYS_A2_30=('").Append(deptLayCode).Append("' + MID(SYS_A2_30,").Append((oriLayCodeLen + 1).ToString()).Append(",LEN(SYS_A2_30))) ");
                    sbCmdText.Append("WHERE SYS_A2_10 IN (SELECT SYS_A2_10 FROM SYS_A2 WHERE SYS_A2_30 LIKE '").Append(oriLayCode).Append("%') AND LEN(SYS_A2_30) > ").Append(oriLayCodeLen.ToString());
                    lstCmdText.Add(sbCmdText.ToString());
                }
                #endregion

                #region 更新部门用户关系
                cmdText = "DELETE FROM SYS_R1 WHERE SYS_R1_20=" + deptId;
                lstCmdText.Add(cmdText);

                string deptUserIds = msDept.includeUsers.key; //部门下用户
                if (!string.IsNullOrEmpty(deptUserIds))
                {
                    if (multiDeptSign == "0") //多部门多职位未开启,则应删除用户原先的部门关系
                    {
                        cmdText = "DELETE FROM SYS_R1 WHERE SYS_R1_10 IN (" + deptUserIds + ")";
                        lstCmdText.Add(cmdText);
                    }

                    string[] userIdArray = deptUserIds.Split(',');
                    foreach (string eUserId in userIdArray)
                    {
                        cmdText = "INSERT INTO SYS_R1 (SYS_R1_10,SYS_R1_20,SYS_R1_30) VALUES (";
                        cmdText += "'" + eUserId + "',";
                        cmdText += "'" + deptId + "','0')";
                        lstCmdText.Add(cmdText);
                    }
                }
                #endregion

                int iexe = DataAccessor.ExecuteNonQuery(lstCmdText);

                if (iexe > 0)
                {
                    lstResult = new List<string> { deptId, "保存成功!" };
                    #region 获取部门是否有下级节点以及部门显示顺序属性
                    sbCmdText.Remove(0, sbCmdText.ToString().Length);
                    sbCmdText.Append("SELECT A.SYS_A2_10 AS DEPTID,A.SYS_A2_60 AS ORDERNO,C.DEPTCOUNT ");
                    sbCmdText.Append("FROM SYS_A2 A INNER JOIN (");
                    sbCmdText.Append("SELECT MID(A1.SYS_A2_30,1,LEN(A2.LAYCODE)) AS LAYCODE,COUNT(*) AS DEPTCOUNT FROM (SYS_A2 A1 ");
                    sbCmdText.Append("INNER JOIN SYS_R5 A3 ON A1.SYS_A2_10=A3.SYS_R5_20) ");
                    sbCmdText.Append("INNER JOIN (SELECT SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_10=").Append(deptId).Append(") A2 ON A1.SYS_A2_30 LIKE '' + A2.LAYCODE + '%' ");
                    sbCmdText.Append("WHERE A3.SYS_R5_10=").Append(msDept.belongOrgan.organId).Append(" AND A1.SYS_A2_70='0' GROUP BY MID(A1.SYS_A2_30,1,LEN(A2.LAYCODE)) ");
                    sbCmdText.Append(") C ON C.LAYCODE=A.SYS_A2_30");

                    string isHasChild = "0";
                    using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                    {
                        if (iReader.Read() && null != iReader[0])
                        {
                            isHasChild = (Int32.Parse(iReader["DEPTCOUNT"].ToString()) > 1) ? "1" : "0";
                            orderNo = iReader["ORDERNO"].ToString();
                        }
                    }

                    lstResult.Add(isHasChild);
                    lstResult.Add(orderNo);

                    #endregion
                }
                else lstResult = new List<string> { "-1", "保存失败:服务器忙请稍后重新尝试操作!", string.Empty, string.Empty };

                lstAlter = null;
            }
            catch (Exception ex)
            {
                StringBuilder sbParam = new StringBuilder();
                int sqlIndex = 1;
                foreach (string eSQL in lstCmdText)
                {
                    sbParam.Append("<SQL" + sqlIndex.ToString()).Append("><![CDATA[").Append(eSQL);
                    sbParam.Append("]]></SQL" + sqlIndex.ToString() + ">");
                    sqlIndex++;
                }
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = sbParam.ToString()
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                sbParam = null;
                lstResult = new List<string> { "-2", "操作失败:详情请参见错误日志!", string.Empty, string.Empty };
            }

            msCurDept = null;
            lstCmdText = null;
            sbCmdText = null;

            return lstResult;
        }

        /// <summary>
        /// 是否变更上级部门
        /// </summary>
        /// <param name="deptId">当前操作的部门Id</param>
        /// <param name="newUpDeptId">新上级部门Id</param>
        /// <returns></returns>
        private List<bool> isAlterUpDept(string deptId, string newUpDeptId)
        {
            bool bAlter = false;

            //获取当前操作部门以及上级部门两个消息对象
            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT SYS_A2_10 AS DEPTID,SYS_A2_30 AS LAYCODE FROM SYS_A2 ");
            if(string.IsNullOrEmpty(newUpDeptId))
                sbCmdText.Append("WHERE SYS_A2_10 IN (").Append(deptId).Append(")");
            else
                sbCmdText.Append("WHERE SYS_A2_10 IN (").Append(deptId + "," + newUpDeptId).Append(")");

            MsDept msCurDept = null;
            MsDept msUpDept = null;
            string tempDeptId = string.Empty;
            try
            {
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        tempDeptId = iReader["DEPTID"].ToString();
                        if (tempDeptId == deptId)
                        {
                            msCurDept = new MsDept
                            {
                                deptId = deptId,
                                layCode = iReader["LAYCODE"].ToString()
                            };
                        }
                        else if (tempDeptId == newUpDeptId)
                        {
                            msUpDept = new MsDept
                            {
                                deptId = newUpDeptId,
                                layCode = iReader["LAYCODE"].ToString()
                            };
                        }
                    }
                }

                if (null == msCurDept || (!string.IsNullOrEmpty(newUpDeptId)) && (null == msUpDept)) throw new Exception();

            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;

                return new List<bool> { false, false };
            }

            #region 校验逻辑
            string curDeptLayCode = msCurDept.layCode;
            int curCodeLen = curDeptLayCode.Length;
            string newUpDeptLayCode = (null != msUpDept) ? msUpDept.layCode : string.Empty;

            if (string.IsNullOrEmpty(newUpDeptId)) //变更为1级部门
            {
                if (msCurDept.layCode.Length == 4) bAlter = false;
                else bAlter = true;
            }
            else
            {
                if (curCodeLen == 4) bAlter = true;
                else
                {
                    string oriUpDeptCode = curDeptLayCode.Substring(0, (curDeptLayCode.Length - 4));
                    if (oriUpDeptCode == newUpDeptLayCode) bAlter = false;
                    else bAlter = true;
                }
            }
            #endregion

            sbCmdText = null;
            msCurDept = null;
            msUpDept = null;
            return new List<bool> { true, bAlter };
        }
        #endregion

    }
}
